<?php

namespace App\Http\Controllers;

use App\Models\PermissionCategory;
use App\Models\Role;
use Illuminate\Http\Request;

class RolesController extends Controller
{
    public function index(){
        $q = Role::query();
        if(\request()->get('start')){
            $q->where('created_at','>=',\request()->get('start'));
        }
        if(\request()->get('end')){
            $q->where('created_at','<=',\request()->get('end'));
        }
        if(\request()->get('name')){
            $q->where('name','like',"%".\request()->get('name')."%");
        }
        if(\request()->get('display_name')){
            $q->where('display_name','like',"%".\request()->get('display_name')."%");
        }
        $roles=$q->withCount('perms')->get();
        \request()->flash();
        if(\request()->wantsJson()){
            return response()->json(['code'=>0,'msg'=>'','count'=>count($roles),'data'=>$roles]);
        }
        return view('rbac.roles.index',compact('roles'));
    }

    public function create()
    {
        $permissionCategories = PermissionCategory::with('permissions')->get();
        return view('rbac.roles.create',compact('permissionCategories'));
    }

    public function store(Request $request)
    {
        try {
            $role = Role::create($request->all());
            $role->perms()->sync($request->get('permission_id'));
            $response = [
                'message' => 'Role created.',
                'data' => $role->toArray(),
            ];

            if ($request->wantsJson()) {
                return response()->json($response);
            }

            return redirect()->back()->with('message', $response['message']);
        } catch (\Exception $e) {
            if ($request->wantsJson()) {
                return response()->json([
                    'error' => true,
                    'message' => $e->getMessage()
                ]);
            }
            return redirect()->back()->withErrors($e->getMessage())->withInput();
        }
    }

    public function edit($id){
        $role = Role::find($id);
        $permission_ids = optional($role->perms)->pluck('id');
        $category_ids = optional($role->perms)->pluck('permission_category_id');
        $category_ids = $category_ids->toArray();

        $permission_ids=$permission_ids->toArray();

        $permissionCategories = PermissionCategory::all();
        return view('rbac.roles.edit',compact('role','permissionCategories','permission_ids','category_ids'));
    }

    public function update(Request $request,$id){
        try {
            $role = Role::find($id);
            $role->update($request->all());
            $role->perms()->sync($request->get('permission_id'));
            $response = [
                'message' => 'role updated.',
                'data'    => $role->toArray(),
            ];
            if ($request->wantsJson()) {
                return response()->json($response);
            }
            return redirect()->back()->with('message', $response['message']);
        } catch (\Exception $e) {
            if ($request->wantsJson()) {
                return response()->json([
                    'error'   => true,
                    'message' => $e->getMessage()
                ]);
            }
            return redirect()->back()->withErrors($e->getMessage())->withInput();
        }
    }

    public function destroy($id){
        $role = Role::find($id);
        $deleted = $role->delete();
        $role->perms()->sync([]);
        if (request()->wantsJson()) {
            return response()->json([
                'message' => 'role deleted.',
                'deleted' => $deleted,
            ]);
        }

        return redirect()->back()->with('message', 'role deleted.');
    }
}
